import Vue from 'vue'
import {
  defaultImg
} from '../config/env'
import {
  getSessionStorage
} from '@/utils/base'
import {
  createdAuth
} from '@/utils/createdAuth'

/*指令测试*/
Vue.directive('demo', {
  bind: function(el, binding, vnode) {
    var s = JSON.stringify
    el.innerHTML =
      'name: ' + s(binding.name) + '<br>' +
      'value: ' + s(binding.value) + '<br>' +
      'expression: ' + s(binding.expression) + '<br>' +
      'argument: ' + s(binding.arg) + '<br>' +
      'modifiers: ' + s(binding.modifiers) + '<br>' +
      'vnode keys: ' + Object.keys(vnode).join(', ')
  }
})

/*权限*/
Vue.directive('auth', function(el, binding) {
  let auth = getSessionStorage('authlist');
  if (!auth) {
    let authlist = {}
    createdAuth(auth, authlist);
    setSessionStorage('authlist', authlist);
    auth = authlist;
  }
  let value = binding.value.toLowerCase();
  if (auth[value] != true) {
    el.style.display = "none";
  }

})

/*默认图片*/
Vue.directive('img-url', async function(el, binding) {
  let imgURL = '';
  if (binding.value instanceof Object) {
    let jsonStr = binding.expression.split(',')[0].replace(/\'/g, '');
    imgURL = checkChild(binding.value, jsonStr);
  } else {
    imgURL = binding.value;
  }

  if (imgURL && typeof(imgURL) != 'undefined') {
    let exist = await imageIsExist(imgURL);
    if (exist) {
      el.setAttribute('src', imgURL);
    } else {
      el.setAttribute('src', defaultImg);
    }
  } else {
    el.setAttribute('src', defaultImg);
  }
})
/***
* 防抖 单位时间只触发最后一次
* 2、应用场景：
* scroll事件滚动
* 浏览器窗口的缩放resize事件
* 搜索框输入查询的时候
* 表单验证
* 按钮的提交事件
*  @param {?Number|300} time - 间隔时间
*  @param {Function} fn - 执行事件
*  @param {?String|"click"} event - 事件类型 例："click"
*  @param {Array} binding.value - [fn,event,time]
*  例：<el-button v-debounce="[reset,`click`,300]">刷新</el-button>
*  也可简写成：<el-button v-debounce="[reset]">刷新</el-button>
*/
Vue.directive('debounce', {
  inserted: function (el, binding) {
      let [fn, event = "click", time = 300] = binding.value
      let timer
      el.addEventListener(event, () => {
          timer && clearTimeout(timer)
          timer = setTimeout(() => fn(), time)
      })
  }
})
/***
*  节流 每单位时间可触发一次
*  第一次瞬间触发，最后一次不管是否达到间隔时间依然触发
*  DOM元素拖拽功能实现
*  计算鼠标移动距离
*  监听scroll滚动事件
*  搜索、提交等按钮功能
* 【考虑到input的change事件】
*  @param {?Number|300} time - 间隔时间
*  @param {Function} fn - 执行事件
*  @param {?String|"click"} event - 事件类型 例："click"
*  @param {Array} binding.value - [fn,event,time]
*  例：<el-button v-throttle="[reset,`click`,300]">刷新</el-button>
*  传递参数则：<el-button v-throttle="[()=>reset(param),`click`,300]">刷新</el-button>
*/
Vue.directive('throttle', {
  inserted: function (el, binding) {
      let [fn, event = "click", time = 300] = binding.value
      let timer, timer_end;
      el.addEventListener(event, () => {
          if (timer) {
              clearTimeout(timer_end);
              return timer_end = setTimeout(() => fn(), time);
          }
          fn();
          timer = setTimeout(() => timer = null, time)
      })
  }
})
/*检查子对象是否为NUll*/
let checkChild = function(obj, str) {
  let _img = null;
  let arr = str.match(/\./g);
  if (!arr) {
    _img = obj[str];
  } else {
    let _i = str.indexOf('.');
    let key = str.substring(0, _i);
    let newobj=obj[key];
    if (newobj instanceof Object == true) {
      let newstr = str.substring(_i+1);
      _img=checkChild(newobj, newstr);
    }
  }
  return _img;
}

/* 检测图片是否存在*/
let imageIsExist = function(url) {
  return new Promise((resolve) => {
    var img = new Image();
    img.onload = function() {
      if (this.complete == true) {
        resolve(true);
        img = null;
      }
    }
    img.onerror = function() {
      resolve(false);
      img = null;
    }
    img.src = url;
  })
}
